package com.example.epidemic_assistant.ui.fragment;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.epidemic_assistant.gen.DaoSession;
import com.android.epidemic_assistant.gen.UserBeanDao;
import com.example.epidemic_assistant.App;
import com.example.epidemic_assistant.R;
import com.example.epidemic_assistant.bean.UserBean;
import com.example.epidemic_assistant.event.MqttGetDataEvent;
import com.example.epidemic_assistant.event.MqttShowToastEvent;
import com.example.epidemic_assistant.mqtt.MqttConnectManager;
import com.example.epidemic_assistant.ui.adapter.TemperatureAdapter;
import com.example.epidemic_assistant.util.NumberUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.MODE_PRIVATE;

/**
 * 主页 - 碎片
 */
public class HomeFragment extends Fragment {

    private static final String TAG = "HomeFragment";

    private TextView mTvRoomId;
    private TextView mTvRemainingDay;
    private TextView mTvDayTemperature;
    private TextView mTvAverageTemperature;
    private RecyclerView mRvTemperature;

    private TemperatureAdapter mTemperatureAdapter;
    private MqttConnectManager mMqttConnectManager;

    private String mUsername;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;

    private App mMyApp;
    private DaoSession mDaoSession;
    private UserBeanDao mUserBeanDao;
    private UserBean mUserBean;
    private ArrayList<String> mTemperatureList = new ArrayList<>();
    private ArrayList<String> mTemperatureDateList = new ArrayList<>();
    private int mRoomId;
    private Button mBtnSatrt;
    private int mYear;
    private int mMonth;
    private int mDay;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        initView(view);
        initData();
        initListener();
        EventBus.getDefault().register(this);
        return view;
    }

    private void initListener() {
        mBtnSatrt.setOnClickListener(view -> {
            mMqttConnectManager.publishMessage("temperature/control", "{\"control\":1}");
        });
    }

    private void initData() {
        mSharedPreferences = getActivity().getSharedPreferences("autoLogin", MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
        String username = mSharedPreferences.getString("username", "");
        if (!username.isEmpty()) {
            mUsername = username;
        } else {
            mUsername = getActivity().getIntent().getExtras().getString("username");
        }

        mMyApp = (App) getActivity().getApplication();
        mDaoSession = mMyApp.getDaoSession();
        mUserBeanDao = mDaoSession.getUserBeanDao();
        List<UserBean> userBeanList = mUserBeanDao.queryBuilder().where(UserBeanDao.Properties.UserName.eq(mUsername)).list();
        for (int i = 0; i < userBeanList.size(); i++) {
            UserBean userBean = userBeanList.get(i);
            if (userBean.getUserName().equals(username)) {
                mUserBean = userBean;
            }
        }

        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH) + 1;
        mDay = calendar.get(Calendar.DAY_OF_MONTH);

        if (mUserBean != null) {
            if (mUserBean.getTemperature() == null) {
                for (int i = 0; i < NumberUtil.getRandomNumber(10); i++) {
                    mTemperatureList.add("3" + NumberUtil.getRandomNumber(9) + "." + NumberUtil.getRandomNumber(9));
                    mTemperatureDateList.add(mYear + "-" + mMonth + "-" + mDay);
                }
                if (mUserBean.getRoomId() != 1) {
                    mUserBean.setRoomId(NumberUtil.getRandomNumber(20));
                    mUserBean.setDay(NumberUtil.getRandomNumber(14));
                    mUserBean.setTemperature(mTemperatureList);
                    mUserBean.setTemperatureDate(mTemperatureDateList);
                    mUserBeanDao.update(mUserBean);
                }
            } else {
                mTemperatureList.addAll(mUserBean.getTemperature());
                mTemperatureDateList.addAll(mUserBean.getTemperatureDate());
            }
            mRoomId = mUserBean.getRoomId();
            mTvRoomId.setText(String.valueOf(mRoomId));
            mTvRemainingDay.setText(String.valueOf(mUserBean.getDay()));
            mTvDayTemperature.setText("36.8");
            if (mTemperatureList != null) {
                float count = 0;
                for (int i = 0; i < mTemperatureList.size(); i++) {
                    String regEx="[^0-9/.]";
                    Pattern p = Pattern.compile(regEx);
                    Matcher m = p.matcher(mTemperatureList.get(i));
                    count = count + Float.parseFloat(m.replaceAll("").trim());
                }
                mTvAverageTemperature.setText(String.valueOf(count / mTemperatureList.size()));
            }
        }

        mRvTemperature.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));
        mTemperatureAdapter = new TemperatureAdapter(requireContext(), mTemperatureList, mTemperatureDateList);
        mRvTemperature.addItemDecoration(new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL));
        mRvTemperature.setAdapter(mTemperatureAdapter);

        mMqttConnectManager = MqttConnectManager.getInstance();
    }

    private void initView(View view) {
        mTvRoomId = view.findViewById(R.id.tv_room_id);
        mTvRemainingDay = view.findViewById(R.id.tv_remaining_day);
        mTvDayTemperature = view.findViewById(R.id.tv_day_temperature);
        mTvAverageTemperature = view.findViewById(R.id.tv_average_temperature);
        mRvTemperature = view.findViewById(R.id.rv_temperature);
        mBtnSatrt = view.findViewById(R.id.btn_start);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMqttGetDataEvent(MqttGetDataEvent event) {
        Toast.makeText(requireContext(), "测温成功，温度为:" + event.getMessage(), Toast.LENGTH_SHORT).show();
        String regEx="[^0-9/.]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(event.getMessage());
        mTvDayTemperature.setText(m.replaceAll("").trim());
        mTemperatureList.add(m.replaceAll("").trim());
        mTemperatureDateList.add(mYear + "-" + mMonth + "-" + mDay);
        mUserBean.setTemperature(mTemperatureList);
        mUserBean.setTemperatureDate(mTemperatureDateList);
        mUserBeanDao.update(mUserBean);
        float count = 0;
        for (int i = 0; i < mTemperatureList.size(); i++) {
            String tem = mTemperatureList.get(i);
            Matcher ms = p.matcher(tem);
            count = count + Float.parseFloat(ms.replaceAll("").trim());
        }
        mTvAverageTemperature.setText(String.valueOf(count / mTemperatureList.size()));
        mTemperatureAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMqttShowToastEvent(MqttShowToastEvent event) {
        Toast.makeText(requireContext(), event.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}